#-*- encoding: utf-8 -*-

from uliweb import functions
from uliweb.orm import get_model
import urllib
import sys  
import traceback
import sqlalchemy

def add_prefix(url):
    from uliweb import settings
    return settings.DOMAINS.static.get('url_prefix', '') + url

def login():

    from . import login

    if request.user:
        next = request.GET.get('next')
        if next:
            return redirect(next)

    if request.method == 'GET':
        #登录失效后，再次登录需要上次的url
        next = request.GET.get('next')

        if next == None:
            next = '/'
        return {'msg':'',"next":next}
    
    if request.method == 'POST':

        username= request.POST.get('username')
        password= request.POST.get('password')
        rememberme= request.POST.get('rememberme')

        f, d = functions.authenticate(username=username, password=password)

        if f:
            request.session.remember = rememberme
            login(username)
            next = urllib.unquote(request.POST.get('next',add_prefix('/')))

            #通过fom方式使用
            #return redirect(next)
            #通过ajax方式使用
            return json({'msg':'','status':200,'url':next})
        else:

            #msg = '账户或密码错误'
            msg = d['msg']
            #form方式
            #return {'msg':msg,'status':500}
            #ajax方式
            return json({'msg':msg,'status':500})


def logout():
    from uliweb.contrib.auth import logout as out
    out()
    next = urllib.unquote(request.GET.get('next', '/'))
    return redirect(next)


def register():
    """
    用户注册,注册账号自动锁定，不允许登录
    """
    if request.method == 'GET':
        return {}
    else:
        User = get_model('user')
        #通知表，用户用户注册后通知管理员
        Notify = get_model('notify')

        username = request.POST.get('username')
        password = request.POST.get('password')
        nickname = request.POST.get('nickname')
        mobile = request.POST.get('mobile')
        email = request.POST.get('email')

        ormdata = User(username=username,
                       nickname=nickname,
                       mobile=mobile,
                       email=email,
                       #密码使用sha1加密
                       password=functions.encrypt_password(password),
                       locked = 1
                       )

        try:
            ormdata.save()

            #消息通知处理
            content = u"%s与%s注册了账号,姓名：%s,手机号：%s,邮箱：%s" % (username,ormdata.date_join,nickname,mobile,email)
            notify_ormdata = Notify(senduser_id = ormdata.id,
                                    content = content,
                                    notify_type = 1
                                    )

            notify_ormdata.save()

            return json({"status":200,"msg":"注册成功"})
        except sqlalchemy.exc.IntegrityError as e:          

            if "Duplicate" in str(e):
                return json({"status":500,"msg":"注册失败,已经存在重复用户"})
        except:
            return json({"status":500,"msg":"注册失败"})

def checkuserinfo():
    """
    检查用户名，邮箱，手机是否存在,用于nice-validator插件
    """
    if request.method == 'GET':
        error("非法访问")
    else:
        filed = request.GET.get('filed')
        username = request.POST.get('username')
        email = request.POST.get('email')
        mobile = request.POST.get('mobile')

        User = get_model('user')

        if filed == 'username':
            ormdata = User.get(User.c.username==username)
            msg = "账号已经存在"
        elif filed == 'email':
            ormdata = User.get(User.c.email==email)
            msg = "邮箱已经存在"            
        elif filed == 'mobile':
            ormdata = User.get(User.c.mobile==mobile)
            msg = "手机号已经存在" 
        else:
            return json({"error":"信息输入错误"})

        if ormdata == None:
            return json({"ok":"验证通过"})
        else:
            return json({"error":msg})